package com.family.system.controller;

import com.family.common.result.Result;
import com.family.model.system.SysMenu;
import com.family.model.vo.AssignMenuVo;
import com.family.system.service.SysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName SysMenuController
 * @Date 2023-05-09 10:20
 * @AUTHOR family
 **/
@Api(tags = "菜单管理")
@RestController
@RequestMapping("/admin/system/sysMenu")
public class SysMenuController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysMenuService sysMenuService;

    @ApiOperation("获取菜单")
    @GetMapping("findNodes")
    @PreAuthorize("hasAuthority('bnt.sysMenu.list')")
    public Result<Object> findNodes() {
        Object menuList = redisTemplate.opsForValue().get("menuList");
        if (menuList != null) {
            return Result.ok(menuList);
        }
        List<SysMenu> list = sysMenuService.findNodes();
        return Result.ok(list);
    }

    @ApiOperation("添加菜单")
    @PostMapping("save")
    @PreAuthorize("hasAuthority('bnt.sysMenu.add')")
    public Result<Object> saveMenu(@RequestBody SysMenu sysMenu) {
        sysMenuService.save(sysMenu);
        redisTemplate.delete("menuList");
        return Result.ok();
    }

    @ApiOperation("删除菜单")
    @DeleteMapping("remove/{id}")
    @PreAuthorize("hasAuthority('bnt.sysMenu.remove')")
    public Result<Object> deleteMenu(@PathVariable Long id) {
        boolean row = sysMenuService.removeById(id);
        if (!row) {
            return Result.fail();
        }
        redisTemplate.delete("menuList");
        return Result.ok();
    }

    @ApiOperation("更新菜单")
    @PutMapping("update")
    @PreAuthorize("hasAuthority('bnt.sysMenu.update')")
    public Result<Object> updateMenu(@RequestBody SysMenu sysMenu) {
        boolean row = sysMenuService.updateById(sysMenu);
        if (!row) {
            return Result.fail();
        }
        redisTemplate.delete("menuList");
        return Result.ok();
    }

    @ApiOperation(value = "根据角色获取菜单")
    @GetMapping("/toAssign/{roleId}")
    @PreAuthorize("hasAuthority('bnt.sysMenu.list')")
    public Result<Object> toAssign(@PathVariable Long roleId) {
        List<SysMenu> list = sysMenuService.findSysMenuByRoleId(roleId);
        return Result.ok(list);
    }

    @ApiOperation(value = "给角色分配权限")
    @PostMapping("/doAssign")
    @PreAuthorize("hasAuthority('bnt.sysRole.assignAuth')")
    public Result<Object> doAssign(@RequestBody AssignMenuVo assignMenuVo) {
        sysMenuService.doAssign(assignMenuVo);
        return Result.ok();
    }

}
